from flask import Blueprint, request, jsonify
from app import db
from .models import DeviceDataUploadLog, UserOperationLog
from AuthComponent import auth_required
from utils import respond, ERRORCODES
from datetime import datetime

bp = Blueprint("LogManager", __name__, url_prefix="/log/")


@auth_required()
@bp.route("/device_data_upload", methods=["POST"])
def log_device_data_upload():
    data = request.get_json()
    device_id = data.get("device_id")
    if not device_id:
        return respond(None, "缺少必要参数 device_id。", ERRORCODES.MISSING_PARAMETERS)

    try:
        upload_time = datetime.now()
        new_log = DeviceDataUploadLog(device_id=device_id, upload_time=upload_time)
        db.session.add(new_log)
        db.session.commit()
        return respond({"message": "设备数据上传日志记录成功"})
    except Exception as e:
        db.session.rollback()
        return respond(
            None, f"设备数据上传日志记录失败: {str(e)}", ERRORCODES.INTERNAL_SERVER_ERROR
        )


@auth_required()
@bp.route("/user_operation", methods=["POST"])
def log_user_operation():
    data = request.get_json()
    user_id = data.get("user_id")
    operation_type = data.get("operation_type")
    if not user_id or not operation_type:
        return respond(None, "缺少必要参数 user_id 或 operation_type。", ERRORCODES.MISSING_PARAMETERS)

    try:
        operation_time = datetime.now()
        device_id = data.get("device_id")
        details = data.get("details")
        new_log = UserOperationLog(
            user_id=user_id,
            operation_type=operation_type,
            operation_time=operation_time,
            device_id=device_id,
            details=details
        )
        db.session.add(new_log)
        db.session.commit()
        return respond({"message": "用户操作日志记录成功"})
    except Exception as e:
        db.session.rollback()
        return respond(
            None, f"用户操作日志记录失败: {str(e)}", ERRORCODES.INTERNAL_SERVER_ERROR
        )